import 'package:flutter_demo1/http/core/dio_adapter.dart';
import 'package:flutter_demo1/http/core/hi_error.dart';
import 'package:flutter_demo1/http/core/hi_net_adapter.dart';
import 'package:flutter_demo1/http/request/base_request.dart';

class HiNet {
  HiNet._();

  static final HiNet _instance = HiNet._();

  static HiNet getInstance() {
    return _instance;
  }

  // 请求
  Future fire(BaseRequest request) async {
    HiNetResponse? response;
    var error;
    try {
      //获取响应内容
      response = await send(request);
    } on HiNetError catch (e) {
      //如果是自定义的网络异常,取出来data作为响应体
      error = e;
      response = e.data;
      printLog(e);
    } catch (e) {
      error = e;
      printLog(e);
    }

    //请求成功后
    if (response == null) {
      printLog(error);
    }

    var result = response?.data;
    printLog(result);

    var status = response?.statusCode;
    status = 200;
    switch (status) {
      case 200:
        return result;
      case 401:
        throw NeedLogin();
      case 403:
        throw NeedAuth(result.toString(), data: result);
      default:
        throw HiNetError(status ?? 500, result.toString(), data: result);
    }
  }

  // 测试用
  // Future<dynamic> send<T>(BaseRequest request) async {
  //   printLog('url:${request.url()}');
  //   printLog('method:${request.httpMethod()}');
  //   request.addHeader("token", "123");
  //   printLog('header:${request.header}');
  //   return Future.value({
  //     "statusCode": 200,
  //     "data": {"code": 0, "message": 'success'},
  //   });
  // }

  //使用mock
  Future<dynamic> send<T>(BaseRequest request) async {
    printLog('url:${request.url()}');
    HiNetAdapter adapter = DioAdapter();
    return adapter.send(request);
  }

  void printLog(log) {
    print('hi_net:${log.toString()}');
  }
}
